package com.atguigu.flink0624.chapter11.function;

import com.atguigu.flink0624.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/20 10:29
 */
public class Flink03_Function_Agg {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("sensor_1", 1000L, 10),
            new WaterSensor("sensor_1", 2000L, 20),
            new WaterSensor("sensor_1", 4000L, 40),
            new WaterSensor("sensor_1", 5000L, 50),
            new WaterSensor("sensor_2", 3000L, 30),
            new WaterSensor("sensor_2", 6000L, 60));
        Table table = tenv.fromDataStream(stream);
        tenv.createTemporaryView("t1", table);
        
        // 1. 在table api中使用
        // 1.1. 内联使用
        /*table
            .groupBy($("id"))
            .select($("id"), call(MySum.class, $("vc")).as("sum_vc"))
            .execute()
            .print();*/
        
        // 1.2. 注册后使用
        
        // 2. 在sql语句中使用
        tenv.createTemporaryFunction("my_avg", MySum.class);
    
        tenv.sqlQuery("select " +
                          "id, " +
                          "my_avg(vc) ma " +
                          "from t1 " +
                          "group by id")
            .execute()
            .print();
        
    }
    
    public static class Sum {
        public Double sum = 0D;
        public Long count = 0L;
    }
    
    public static class MySum extends AggregateFunction<Double, Sum> {
        
        @Override
        public Double getValue(Sum acc) {
            return acc.sum * 1.0 / acc.count;
        }
        
        @Override
        public Sum createAccumulator() {
            return new Sum();
        }
        
        public void accumulate(Sum acc, Double value) {
            acc.sum += value;
            acc.count++;
        }
    }
    
}
